C++ Destructors: Cleanup Operations When Objects Are Destroyed
The destructor in C++ is a cleanup function automatically invoked when an object is destroyed, used to release dynamic resources (such as memory and files) and prevent resource leaks. Its definition format is: it has the same name as the class but starts with a `~`, with no parameters or return value. A class can only have one destructor, and it cannot be overloaded. The core function is to clean up resources: for example, dynamically allocated memory (released when using `delete`), open files (closed), etc. For instance, an array class `Array` uses `new` to allocate memory during construction and `delete[]` to release it during destruction, thus avoiding memory leaks. Calling timing: when an object leaves its scope (e.g., a local variable), when a dynamic object is deleted with `delete`, or when a temporary object is destroyed. The default destructor is generated by the compiler, which automatically calls the destructors of member objects. Precautions: It cannot be explicitly called. A virtual destructor (declaring the base class destructor as `virtual`) is necessary when a base class pointer points to a derived class object to ensure proper cleanup of derived class resources. Summary: The destructor is a cleanup tool at the "end of life" of an object, called automatically. Proper use can avoid resource waste and memory leaks.
Read More